package com.cloud.gateway.route;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.cloud.gateway.properties.NacosRouteProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * nacos配置文件类
 *
 * @author 王霄
 * @date 2022/8/13 17:52
 */
@Configuration
@Slf4j
public class NacosRouteConfig {

    @Bean
    public ObjectMapper getObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        return objectMapper;
    }

    @Bean
    public ConfigService configService(NacosRouteProperties nacosRouteProperties) {
        Properties properties = new Properties();
        properties.setProperty("serverAddr", nacosRouteProperties.getNacosServerAddress());
        properties.setProperty("namespace", nacosRouteProperties.getRouteNamespace());
        try {
            return NacosFactory.createConfigService(properties);
        } catch (NacosException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Bean
    public NacosRouteDefinitionRepository nacosRouteDefinitionRepository(NacosRouteProperties nacosRouteProperties,
                                                                         ObjectMapper objectMapper,
                                                                         ApplicationEventPublisher publisher,
                                                                         ConfigService configService) {
        return NacosRouteDefinitionRepository.builder()
                .properties(nacosRouteProperties)
                .objectMapper(objectMapper)
                .publisher(publisher)
                .configService(configService).build();
    }
}